package com.dabaozhan.modules.wx_app.facade.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dabaozhan.common.exception.RRException;
import com.dabaozhan.common.utils.DateUtils;
import com.dabaozhan.modules.wx_app.base.PageResult;
import com.dabaozhan.modules.wx_app.dao.SiteCategoryMapper;
import com.dabaozhan.modules.wx_app.entity.FormQueryEntity;
import com.dabaozhan.modules.wx_app.entity.HistogramRequestEntity;
import com.dabaozhan.modules.wx_app.entity.HistogramResponseEntity;
import com.dabaozhan.modules.wx_app.entity.PurchaseFormEntity;
import com.dabaozhan.modules.wx_app.entity.SaleFormEntity;
import com.dabaozhan.modules.wx_app.entity.SiteCategoryEntity;
import com.dabaozhan.modules.wx_app.entity.TodayDataEntity;
import com.dabaozhan.modules.wx_app.entity.FormPersonResponseEntity;
import com.dabaozhan.modules.wx_app.enums.ResponseCodeEnum;
import com.dabaozhan.modules.wx_app.facade.PurchaseFormFacade;
import com.dabaozhan.modules.wx_app.service.PurchaseFormService;
import com.dabaozhan.modules.wx_app.service.SaleFormService;

@Service("purchaseFormFacade")
public class PurchaseFormFacadeImpl implements PurchaseFormFacade{
	
	@Autowired
	private PurchaseFormService purchaseFormService;
	@Autowired
	private SaleFormService saleFormService;
	@Autowired
	private SiteCategoryMapper siteCategoryMapper;

	@Override
	public PageResult<List<FormPersonResponseEntity>> getPurchaseList(FormQueryEntity entity) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int tomeSection = entity.getTimeSection();
		Date beginDate = DateUtils.getBeginDate(tomeSection);
		Date endDate = DateUtils.getEndDate(tomeSection);
		entity.setBeginTime(format.format(beginDate));
		entity.setEndTime(format.format(endDate));
		List<PurchaseFormEntity> list = purchaseFormService.getPurchaseList(entity);
		if(CollectionUtils.isEmpty(list)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		List<FormPersonResponseEntity> resultList = new ArrayList<FormPersonResponseEntity>();
		for(PurchaseFormEntity p:list){
			String supplierId = p.getSupplierId();
			if(StringUtils.isBlank(supplierId)){
				continue;
			}
			//resultList 中没有这个供应商
			if(!judgeExist(resultList,supplierId)){
				List<PurchaseFormEntity> limitList = list.stream().filter(l->supplierId.equals(l.getSupplierId())).collect(Collectors.toList());
				BigDecimal totalPrice =  limitList.stream().map(PurchaseFormEntity::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
				BigDecimal totalWeight =  limitList.stream().map(PurchaseFormEntity::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
				BigDecimal averagePrice = null;
				if(totalWeight.compareTo(BigDecimal.ZERO) !=0){
					averagePrice = totalPrice.divide(totalWeight, 2,BigDecimal.ROUND_DOWN);
				}
				int purchaseTime = limitList.size();
				FormPersonResponseEntity pEntity = new FormPersonResponseEntity();
				pEntity.setName(p.getName());
				pEntity.setTotalPrice(totalPrice);
				pEntity.setTotalWeight(totalWeight);
				pEntity.setAveragePrice(averagePrice);
				pEntity.setTimes(purchaseTime);
				pEntity.setSupplierId(supplierId);
				resultList.add(pEntity);
			}
		}
		//查询开始区间
		int beginIndex = (entity.getPage()-1)*entity.getSize();
		//查询结束区间
		int endIndex = entity.getPage()*entity.getSize();
		//按照重量排序从大到小排序
		Comparator<FormPersonResponseEntity> comparator = (h1, h2) -> h1.getTotalWeight().compareTo(h2.getTotalWeight());
		resultList.sort(comparator.reversed());
		Integer totalCount = resultList.size();
		PageResult<List<FormPersonResponseEntity>> pageResult = new PageResult<List<FormPersonResponseEntity>>();
		pageResult.setTotal(totalCount);
		
		//分页限制判断 理论上不会进入此逻辑
		if(beginIndex>totalCount-1){
			pageResult.setListData(null);
		}else{
			List<FormPersonResponseEntity> responseList= resultList.subList(beginIndex, endIndex > totalCount?totalCount:endIndex);
			pageResult.setListData(responseList);
		}
		return pageResult;
	}
	
	//判断 是否存在  存在返回 true  不存在返回false
	private static boolean judgeExist(List<FormPersonResponseEntity> l,String supplierId){
		boolean r = false;
		for(FormPersonResponseEntity entity:l){
			if(supplierId.equals(entity.getSupplierId())){
				return true;
			}
		}
		return r;
	}
	
	@Override
	public List<HistogramResponseEntity> getPurchaseHistogram(HistogramRequestEntity entity) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		int tomeSection = entity.getTimeSection();
		Date beginDate = DateUtils.getBeginDate(tomeSection);
		Date endDate = DateUtils.getEndDate(tomeSection);
		entity.setBeginTime(format.format(beginDate));
		entity.setEndTime(format.format(endDate));
		FormQueryEntity formQuery = new FormQueryEntity();
		formQuery.setUserId(entity.getUserId());
		formQuery.setBeginTime(entity.getBeginTime());
		formQuery.setEndTime(entity.getEndTime());
		List<PurchaseFormEntity> list = purchaseFormService.getPurchaseList(formQuery);
		if(CollectionUtils.isEmpty(list)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		List<SiteCategoryEntity> categoryList = siteCategoryMapper.getCategoryListByUserId(entity.getUserId());
		List<HistogramResponseEntity> resultList = new ArrayList<HistogramResponseEntity>();
		for(PurchaseFormEntity pfe:list){
			String categoryId = pfe.getCategoryId();
			String parentId = pfe.getParentId();
			if(StringUtils.isBlank(categoryId) || StringUtils.isBlank(categoryId)){
				continue;
			}
			if(!judgeCategoryIdExist(resultList,parentId,categoryId)){
				List<PurchaseFormEntity> limitList = list.stream().filter(l->categoryId.equals(l.getCategoryId())).collect(Collectors.toList());
				BigDecimal totalWeight =  limitList.stream().map(PurchaseFormEntity::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
				HistogramResponseEntity responseEntity = new HistogramResponseEntity();
				responseEntity.setParentId(pfe.getParentId());
				responseEntity.setCategoryId(categoryId);
				responseEntity.setCategoryName(getCategoryName(categoryList,parentId,categoryId));
				responseEntity.setTotalWeight(totalWeight);
				resultList.add(responseEntity);
			}
		}
		if(CollectionUtils.isEmpty(resultList)){
			throw new RRException(ResponseCodeEnum.ResponseCode_400.getCode(),ResponseCodeEnum.ResponseCode_400.getDescription());
		}
		//按照重量排序从大到小排序
		Comparator<HistogramResponseEntity> comparator = (h1, h2) -> h1.getTotalWeight().compareTo(h2.getTotalWeight());
		resultList.sort(comparator.reversed());
		return resultList;
	}
	
	public static String getCategoryName(List<SiteCategoryEntity> list,String parentId,String categoryId){
		if(CollectionUtils.isEmpty(list)||StringUtils.isBlank(parentId)||StringUtils.isBlank(categoryId)){
			return "";
		}
		List<SiteCategoryEntity> selectList = list.stream().filter(l->(categoryId.equals(l.getCategoryId()) && parentId.equals(l.getParentId()))).collect(Collectors.toList());
		if(CollectionUtils.isEmpty(selectList)){
			return "";
		}else{
			return selectList.get(0).getName();
		}
	}
	
	//判断 是否存在  存在返回 true  不存在返回false
	public static boolean judgeCategoryIdExist(List<HistogramResponseEntity> l,String parentId,String categoryId){
		boolean r = false;
		if(CollectionUtils.isEmpty(l) || StringUtils.isBlank(parentId) || StringUtils.isBlank(categoryId)){
			return r;
		}
		for(HistogramResponseEntity entity:l){
			if(categoryId.equals(entity.getCategoryId()) && parentId.equals(entity.getParentId())){
				return true;
			}
		}
		return r;
	}

	@Override
	public TodayDataEntity getTodayData(String userId) {
		TodayDataEntity response = new TodayDataEntity();
		response.setPurchasePrice(BigDecimal.ZERO);
		response.setPurchaseWeight(BigDecimal.ZERO);
		response.setSalePrice(BigDecimal.ZERO);
		response.setSaleWeight(BigDecimal.ZERO);
		FormQueryEntity entity = new FormQueryEntity();
		entity.setUserId(userId);
		entity.setBeginTime(todayFirstDate());
		entity.setEndTime(todayLastDate());
		List<PurchaseFormEntity> purList = purchaseFormService.getPurchaseList(entity);
		if(!CollectionUtils.isEmpty(purList)){
			BigDecimal totalWeight =  purList.stream().map(PurchaseFormEntity::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
			BigDecimal totalPrice =  purList.stream().map(PurchaseFormEntity::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
			response.setPurchaseWeight(totalWeight);
			response.setPurchasePrice(totalPrice);
			
		}
		List<SaleFormEntity> salseList = saleFormService.getSaleList(entity);
		if(!CollectionUtils.isEmpty(salseList)){
			BigDecimal saleTotalWeight =  salseList.stream().map(SaleFormEntity::getTotalWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
			BigDecimal saleTotalPrice =  salseList.stream().map(SaleFormEntity::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
			response.setSaleWeight(saleTotalWeight);
			response.setSalePrice(saleTotalPrice);
		}
		return response;
	}
	
	public static String todayFirstDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Calendar calendar = Calendar.getInstance();
	    calendar.set(Calendar.HOUR_OF_DAY, 0);
	    calendar.set(Calendar.MINUTE, 0);
	    calendar.set(Calendar.SECOND, 0);
	    Date date = calendar.getTime();
	    return format.format(date);
	}

	public static String todayLastDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Calendar calendar = Calendar.getInstance();
	    calendar.set(Calendar.HOUR_OF_DAY, 23);
	    calendar.set(Calendar.MINUTE, 59);
	    calendar.set(Calendar.SECOND, 59);
	    Date date = calendar.getTime();
	    return format.format(date);
	}

}
